<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索和操作区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-select
            v-model="queryParams.waterPlantId"
            placeholder="请选择水厂"
            clearable
            @change="handleSearch"
            style="width: 100%"
          >
            <el-option
              v-for="item in factoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-col>
        <el-col :span="16" class="text-right">
          <el-button type="primary" @click="showAddDialog">新增配置</el-button>
        </el-col>
      </el-row>

      <!-- 配置表格 -->
      <el-table
        :data="configList"
        border
        class="mt-2"
        v-loading="loading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
      >
        <el-table-column label="指标类型" prop="indicatorType" />
        <el-table-column label="水厂">
          <template #default="{ row }">
            {{ getDictLabel(factoryOptions, row.waterPlantId) }}
          </template>
        </el-table-column>
        <el-table-column label="正常值范围" prop="normalRange" />
        <el-table-column label="警戒值" prop="warningThreshold" />
        <el-table-column label="报警值" prop="alertThreshold" />
        <el-table-column label="正常颜色">
          <template #default="{ row }">
            <div class="color-display" :style="{ backgroundColor: row.normalColor }"></div>
            {{ row.normalColor }}
          </template>
        </el-table-column>
        <el-table-column label="警戒颜色">
          <template #default="{ row }">
            <div class="color-display" :style="{ backgroundColor: row.warningColor }"></div>
            {{ row.warningColor }}
          </template>
        </el-table-column>
        <el-table-column label="报警颜色">
          <template #default="{ row }">
            <div class="color-display" :style="{ backgroundColor: row.alertColor }"></div>
            {{ row.alertColor }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="currentConfig"
        label-width="120px"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="指标类型" prop="indicatorType">
          <el-input v-model="currentConfig.indicatorType" placeholder="请输入指标类型" />
        </el-form-item>
        <el-form-item label="水厂" prop="waterPlantId">
          <el-select
            v-model="currentConfig.waterPlantId"
            placeholder="请选择水厂"
            style="width: 100%"
          >
            <el-option
              v-for="item in factoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="+item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="正常值范围" prop="normalRange">
          <el-input v-model="currentConfig.normalRange" placeholder="示例: 0.5-1.5" />
        </el-form-item>
        <el-form-item label="警戒值" prop="warningThreshold">
          <el-input-number v-model="currentConfig.warningThreshold" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="报警值" prop="alertThreshold">
          <el-input-number v-model="currentConfig.alertThreshold" :min="0" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="正常颜色" prop="normalColor">
          <el-color-picker v-model="currentConfig.normalColor" show-alpha />
          <el-input v-model="currentConfig.normalColor" placeholder="如#00FF00" class="ml-2" />
        </el-form-item>
        <el-form-item label="警戒颜色" prop="warningColor">
          <el-color-picker v-model="currentConfig.warningColor" show-alpha />
          <el-input v-model="currentConfig.warningColor" placeholder="如#FFFF00" class="ml-2" />
        </el-form-item>
        <el-form-item label="报警颜色" prop="alertColor">
          <el-color-picker v-model="currentConfig.alertColor" show-alpha />
          <el-input v-model="currentConfig.alertColor" placeholder="如#FF0000" class="ml-2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getFactoryList,
  getIndicatorColorConfigList,
  getIndicatorColorConfigDetail,
  addIndicatorColorConfig,
  updateIndicatorColorConfig,
  deleteIndicatorColorConfig
} from '@/api/prod_operate/sys_setting/cockpit/color_settings'

// 加载状态
const loading = ref(false)

// 水厂选项
const factoryOptions = ref([])

// 配置列表数据
const configList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  waterPlantId: ''
})

// 当前操作的配置
const currentConfig = reactive({
  colorConfigId: '',
  indicatorType: '',
  waterPlantId: '',
  normalRange: '',
  warningThreshold: 0,
  alertThreshold: 0,
  normalColor: '#00FF00',
  warningColor: '#FFFF00',
  alertColor: '#FF0000'
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增配置')
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  indicatorType: [
    { required: true, message: '请输入指标类型', trigger: 'blur' }
  ],
  waterPlantId: [
    { required: true, message: '请选择水厂', trigger: 'change' }
  ],
  normalRange: [
    { required: true, message: '请输入正常值范围', trigger: 'blur' }
  ],
  warningThreshold: [
    { required: true, message: '请输入警戒值', trigger: 'blur' }
  ],
  alertThreshold: [
    { required: true, message: '请输入报警值', trigger: 'blur' }
  ],
  normalColor: [
    { required: true, message: '请选择正常颜色', trigger: 'change' }
  ],
  warningColor: [
    { required: true, message: '请选择警戒颜色', trigger: 'change' }
  ],
  alertColor: [
    { required: true, message: '请选择报警颜色', trigger: 'change' }
  ]
})

// 根据字典值获取标签
const getDictLabel = (options, value) => {
  const item = options.find(item => item.dictValue == value)
  return item ? item.dictLabel : value
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true
    
    // 获取水厂列表
    const factoryRes = await getFactoryList()
    factoryOptions.value = factoryRes.data
    
    // 获取配置列表
    await fetchConfigList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取配置列表
const fetchConfigList = async () => {
  try {
    loading.value = true
    const res = await getIndicatorColorConfigList(queryParams)
    configList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchConfigList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchConfigList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchConfigList()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增配置'
  resetCurrentConfig()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getIndicatorColorConfigDetail(row.colorConfigId)
    Object.assign(currentConfig, res.data)
    dialogTitle.value = '编辑配置'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前配置
const resetCurrentConfig = () => {
  currentConfig.colorConfigId = ''
  currentConfig.indicatorType = ''
  currentConfig.waterPlantId = ''
  currentConfig.normalRange = ''
  currentConfig.warningThreshold = 0
  currentConfig.alertThreshold = 0
  currentConfig.normalColor = '#00FF00'
  currentConfig.warningColor = '#FFFF00'
  currentConfig.alertColor = '#FF0000'
}

// 确认保存
const confirmSave = async () => {
  try {
    await formRef.value.validate()
    
    if (dialogTitle.value === '新增配置') {
      await addIndicatorColorConfig(currentConfig)
      ElMessage.success('新增配置成功')
    } else {
      await updateIndicatorColorConfig(currentConfig)
      ElMessage.success('修改配置成功')
    }
    
    dialogVisible.value = false
    fetchConfigList()
  } catch (error) {
    console.error('保存配置失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该配置吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteIndicatorColorConfig(row.colorConfigId)
      ElMessage.success('删除成功')
      fetchConfigList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.mt-2 {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容居中对齐 */
:deep(.el-table th),
:deep(.el-table td) {
  text-align: center !important;
}

/* 表格单元格内边距 */
:deep(.el-table .cell) {
  padding: 8px;
}

.color-display {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 8px;
  vertical-align: middle;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.ml-2 {
  margin-left: 8px;
}
</style>